package bin_tree.oj;

public class Num236 {
    TreeNode lca;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }
        //从根节点出发进行向后遍历，找到lca
        find(root,p,q);
        return lca;
    }
    //在方法外面找，因为为递归方法，每个节点都要处理。尤其是判空时
    private boolean find(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return false;
        }
        int left = find(root.left,p,q) ? 1 : 0;
        int right = find(root.right,p,q) ? 1 : 0;
        int mid = (root == p || root == q) ? 1 : 0;
        if(left + right + mid == 2){
            lca = root;
            return true;
        }
        return (left + right + mid) > 0;
    }
}
